import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_project/config/common_empty_view.dart';
import '../config/asphere_refresh_utils.dart';
import '../config/common_string_config.dart';
import '../requst/dio_http_utils.dart';
import 'home_video_item_view.dart';
import 'home_video_list_model.dart';

enum HomeTabType {
  homeTabHotType,
  homeTabAllType,
}

class HomeTabListPage extends StatefulWidget {
  final HomeTabType type;

  const HomeTabListPage({required this.type, super.key});

  @override
  State<HomeTabListPage> createState() => _HomeTabListPageState();
}

class _HomeTabListPageState extends State<HomeTabListPage> {
  List dataList = [];
  int page = 0;
  EasyRefreshController easyRefreshController = EasyRefreshController();

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 10),
      child: dataList.isNotEmpty
          ? AsphereRefreshUtils.refreshWidget(
              context: context,
              refreshController: easyRefreshController,
              startRefresh: () {
                loadFirstPageData();
              },
              startLoad: () {
                page++;
                getListData();
              },
              childWidget: GridView.builder(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 10,
                  ),
                  itemCount: dataList.length,
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                      crossAxisSpacing: 10,
                      mainAxisSpacing: 10,
                      childAspectRatio: 10 / 11),
                  itemBuilder: (context, index) {
                    VideoListVideosModel itemModel = dataList[index];
                    return HomeVideoItemView(
                      itemModel: itemModel,
                      tapAction: () {
                        CommonStringConfig.likeEventBus
                            .fire({"isRefreshCollectPage": true}); //
                      },
                    );
                  }))
          : CommonEmptyView(
              refreshBlock: () {
                getListData();
              },
            ),
    );
  }

  @override
  void initState() {
    super.initState();
    getListData();
    CommonStringConfig.likeEventBus.on<Map>().listen((event) {
      if (event['isRefreshHomePage'] == true) {
        loadFirstPageData();
      }
    });
  }

  loadFirstPageData() {
    if (dataList.isNotEmpty) {
      dataList.clear();
    }
    page = 0;
    getListData();
  }

  getListData() async {
    Map<String, dynamic>? dataMap = {
      'Limit': 6,
      'MediaType': 1,
      'Offset': page * 6,
      'SortFieldName': 'Likes',
      'SortType': 'desc'
    };
    if (widget.type == HomeTabType.homeTabHotType) {
      // 获取当前时间戳
      DateTime now = DateTime.now();
      // 计算7天以前的时间戳
      DateTime sevenDaysAgo = now.subtract(const Duration(days: 7));
      dataMap['StartTime'] = sevenDaysAgo.millisecondsSinceEpoch;
    }
    debugPrint(dataMap.toString());
    String apiUrl = 'media/getAllMedias';
    var res = await HttpDioUtils.request(apiUrl, params: dataMap);
    if (res != null) {
      VideoListModel videoListModel = VideoListModel.fromJson(res);
      List videoList = videoListModel.resp?.videos ?? [];
      if (page > 0 && videoList.isEmpty) {
        easyRefreshController.finishLoad(IndicatorResult.noMore, true);
        return;
      }
      dataList.addAll(videoListModel.resp?.videos ?? []);
      if (mounted) {
        setState(() {});
      }
    }
  }
}
